<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.keyword" placeholder="关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="highQuery">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="success" @click="onSale" :disabled="this.sels.length===0">上架</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="warning" @click="handleAdd" :disabled="this.sels.length===0">下架</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="products" highlight-current-row v-loading="listLoading"
				  @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="name" label="名称" width="150" sortable>
			</el-table-column>
            <el-table-column prop="saleprice" label="售价" width="150" sortable>
            </el-table-column>
			<el-table-column prop="state" label="状态" width="150" sortable>
                <template scope="scope">
                    <span style="color: red" v-if="scope.row.state==0">下架</span>
                    <span style="color: green" v-else-if="scope.row.state==1">上架</span>
                </template>
			</el-table-column>
			<el-table-column prop="onsaletime" label="上架时间" width="150" sortable>
			</el-table-column>
			<el-table-column prop="offsaletime" label="下架时间" width="150" sortable>
			</el-table-column>
			<el-table-column prop="salecount" label="销量" width="150" sortable>
			</el-table-column>
			<el-table-column label="操作">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange"
						   :page-size="pageSize" :total="totals" :current-page="currentPage" style="float:right;">
			</el-pagination>
		</el-col>

		<!--添加和修改对话框-->
		<el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
			<el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
				<!--
					prop="name" ，如果当前表单项需要验证，必须要加
				 -->
				<el-form-item label="名称" prop="name">
					<el-input v-model="saveForm.name" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="售价">
					<el-input v-model="saveForm.saleprice" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="原价">
					<el-input v-model="saveForm.costprice" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="商品图片">
					<el-upload
							class="upload-demo"
							action="/api/dfs/upload"
							:on-remove="handleRemove"
							:on-success="handleSuccess"
							:limit="5"
							:file-list="fileList"
							list-type="picture">
						<el-button size="small" type="primary">点击上传</el-button>
						<div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
					</el-upload>
				</el-form-item>
				<el-form-item label="商品介绍">
					<!--<el-input v-model="saveForm.detail.intro" auto-complete="off"></el-input>-->
					<quill-editor  v-model="saveForm.detail.intro"  :options="editorOption"></quill-editor>

				</el-form-item>
				<el-form-item label="预约须知">
					<!--<el-input v-model="saveForm.detail.orderNotice" auto-complete="off"></el-input>-->
					<quill-editor  v-model="saveForm.detail.orderNotice" :options="editorOption" ></quill-editor>
				</el-form-item>



			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="saveFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
			</div>
		</el-dialog>

	</section>
</template>

<script>
	import util from '../../common/js/util'
	//引入富文本编辑器
    import { quillEditor } from 'vue-quill-editor'
	//引入相关的样式文件
    import 'quill/dist/quill.core.css'
    import 'quill/dist/quill.snow.css'
    import 'quill/dist/quill.bubble.css'
	//引入自定义上传路径的配置文件
    import quillConfig from '../../common/js/quill-config'
	export default {
        components: {
            quillEditor
        },
		data() {
			return {
                editorOption:quillConfig,//引入配置文件进行文件上传
				filters: {
                    keyword: ''				//高级查询的关键字
				},
				products: [],			// then中，成功之后赋值
				totals: 0, 					// then中，成功之后赋值
                currentPage: 1,				// 单击事件：handleCurrentChange()
				pageSize:5,					// 直接写死的
				listLoading: false,			//列表显示忙等框
				sels: [],					//批量删除时保存已经选中的对象
                title: "",					//添加和修改的对话框动态显示
				managers:[],  				//保存所有的经理 = 员工
				deptTree: [],				//保存所有的父部门【parent_id=null】和所有子部门

				//编辑模态框模型数据
				saveFormVisible: false,
				saveLoading: false,
				saveFormRules: {
					name: [
						{ required: true, message: '请输入部门名称', trigger: 'blur' }
					],
                    sn: [ //prop属性
                        { required: true, message: '请输入部门编号', trigger: 'blur' }
                    ]
				},
				//添加和修改界面数据清空
				saveForm: {
					id: null,
					name: '',
					saleprice:0,
					costprice:0,
					resources:'',
                    detail:{
					    id:null,
						intro:'',
						orderNotice:''
					}
				},
                fileList:[]
			}
		},
		methods: {
            onSale(){
                var ids = this.sels.map(item => item.id);// [1,2,5]

                this.$confirm('确认上架选中的商品？', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;

                    this.$http.patch("/product",ids).then(res=>{
                        this.listLoading = false;
                        if(res.data.success){
                            this.$message({
                                message: '上架成功',
                                type: 'success'
                            });
                            this.getProducts();
                        }else{
                            this.$message({
                                message: res.data.msg,
                                type: 'error'
                            });
                        }
                    }).catch(res=>{
                        alert("系统错误")
                    });
                }).catch(() => {

                });
			},
            handleSuccess(response, file, fileList){
               // this.saveForm.resources= response.resultObject;
                //多图片的处理
                // console.debug(response)
                // console.debug(file)
                // console.debug(fileList)
				//使用for循环 fileList  取出每一个 file--response--resultObject
				let resultStr='';
				for(var i=0;i<fileList.length;i++){
					if (i==fileList.length-1){
                       resultStr+=fileList[i].response.resultObject;
					}else{
                        resultStr+=fileList[i].response.resultObject+",";
					}
				}
                this.saveForm.resources=resultStr;
            },

            handleRemove(file, fileList) {

			},
		    //分页时点击页码时触发
			handleCurrentChange(val) {
				this.currentPage = val;            //改变当前页
				this.getProducts();
			},

			//高级查询
			highQuery(){
                this.currentPage = 1;            //每次点击高级查询都将当前页设置为1
                this.getProducts();
            },

			//获取部门列表
            getProducts() {
				let para = {
					currentPage: this.currentPage,  //分页_当前页
                    pageSize:this.pageSize,         //分页_每页显示的条数
                    keyword: this.filters.keyword   //高级查询的关键字
				};
				this.listLoading = true;            //显示忙等框

                this.$http.post("/product",para)
                    .then(res=>{
                        //1.去掉忙等框
                        this.listLoading = false;
                        //2.给模型数据products赋值
                        this.products = res.data.data;
                        //3.给模型数据totals赋值
                        this.totals = res.data.totals;
                    })
                    .catch(res=>{
                        alert("系统错误");
                    })
			},

			//删除 //http://localhost:8080/department/1   --  delete
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => { //点确认执行里面的代码
					this.listLoading = true;
                    let para = "/department/"+row.id;
                    this.$http.delete(para).then(res=>{//删除成功
                        //1.关闭忙等框
                        this.listLoading = false;
                        if(res.data.success){
                            //2.提示删除成功
                            this.$message({
                                message: '删除成功',
                                type: 'success'
                            });
                            //如果删除的当前页只有一条数据的时候：就应该放当前页 = 当前页-1
                            if(this.currentPage>1 && (this.totals-1)%this.pageSize==0){
                                this.currentPage = this.currentPage - 1;
                            }
                            this.getProducts();//3.重新加载数据
                        }else{
                            this.$message({
                                message: res.data.msg,
                                type: 'error'
                            });
						}
                    }).catch(res=>{ //如果出现跨域问题，连接后端服务器问题，传参错误
                        alert("系统错误");
                    })
				}).catch(() => {

				});
			},

			//显示编辑界面
			handleEdit: function (index, row) {
				this.title = "编辑";
                this.saveForm = Object.assign({}, row); //做回显  -  克隆
				//图片的回显 row.resources
				this.fileList=[];
				if(row.resources){
                    let arr = row.resources.split(",");
					for(var i=0;i<arr.length;i++){
						//把对象放到数组里面
                        this.fileList.push({
                            name:'fiasf.jpg',
                            url:'http://115.159.217.249:8888'+arr[i]
                        })

					}

				}
                this.saveFormVisible = true; //显示对话框
            },

			//显示新增界面
			handleAdd: function () {
                this.title = "添加";
                this.saveForm = {
                    id: null,
                    name: '',
                    saleprice:0,
                    costprice:0,
                    resources:'',
                    detail:{
                        id:null,
                        intro:'',
                        orderNotice:''
                    }
				};

                this.saveFormVisible = true;
            },

			//点击新增和修改的提交按钮时触发的方法
			saveSubmit: function () {
                //所有的ref属性 其中的 ref="saveForm" 进行验证
                this.$refs.saveForm.validate((valid) => {
					if (valid) { //如果验证成功  - 才执行if里面的代码
						this.$confirm('确认提交吗？', '温馨提示', {}).then(() => {
							this.saveLoading = true; //打开忙等框
							let para = Object.assign({}, this.saveForm);//将数据克隆给空对象，并将对象赋值给para变量
                            this.$http.put("/product",para).then(res=>{
                                this.saveLoading = false;//关闭忙等框
								if(res.data.success){
                                    this.$message({
                                        message: '提交成功',
                                        type: 'success'
                                    });
                                    this.$refs['saveForm'].resetFields();//重置对话框
                                    this.saveFormVisible = false;//关闭对话框
                                    this.getProducts();//重新加载数据
								}else{
                                    this.$message({
                                        message: res.data.msg,
                                        type: 'error'
                                    });
								}
							}).catch(res=>{
							    alert("系统异常，请稍后重试!");
							})
						});
					}
				});
			},

			//批量删除时获取选中的对象
			selsChange: function (sels) {
				this.sels = sels;//会获取选中的对象
			},

			//批量删除
			batchRemove: function () {
				var ids = this.sels.map(item => item.id);// [1,2,5]

				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;

					this.$http.patch("/department",ids).then(res=>{
                        this.listLoading = false;
                        if(res.data.success){
                            this.$message({
                                message: '删除成功',
                                type: 'success'
                            });
                            this.currentPage = 1;
                            this.getProducts();
						}else{
                            this.$message({
                                message: res.data.msg,
                                type: 'error'
                            });
						}
					}).catch(res=>{
					    alert("系统错误")
					});
				}).catch(() => {

				});
			},

			//加载所有的员工【经理】
			getManagers(){
			    this.$http.get("/employee").then(res=>{
			        if(res){
                        this.managers = res.data;
                    }
				})
			},

			//加载部门树[一级部门以及所属的二级部门]
            getDeptTree(id){
			    if(id==""){
			        id=0;
				}
                this.$http.get("/department/deptTree/"+id).then(res=>{
                    if(res){
                        this.deptTree = res.data;
                    }
                })
            }
		},
		mounted() { //页面一加载就调用此方法
            this.getProducts();
		}
	}

</script>

<style scoped>

</style>